args Controls

********************************************************************************
* Wage variance decomposition
********************************************************************************

preserve

* residualize log wages
foreach a of numlist 23 33 42 46 50 55{
qui reg lwage_I`a' `Controls' [pweight=1/pObs_I`a']
local r=e(rmse)
predict uit_I`a', resid
replace uit_I`a'=. if  uit_I`a'>(3.5*e(rmse))|uit_I`a'<(-3.5*e(rmse))
}

* reshape
reshape long lwage_I uit_I pObs_I, i(NCDSID) j(age)
ge sweep=age
recode sweep (23=4) (33=5) (42=6) (46=7) (50=8) (55=9)
egen id=group(NCDSID)
rename uit_I uit

ge Drop=uit==.
bys NCDSID Drop: ge N=_N
replace Drop=1 if N==1
replace uit=. if N==1
bys NCDSID: egen mDrop=min(Drop)
ge Obs_WS =1-mDrop
bys NCDSID: ge nn=_n
ge t =  MissingMP_0
replace MissingMP_0 = 0
logit Obs_WS $HDC_0 if nn==1
replace MissingMP_0=t
drop t
predict pObs_WS

* standardize by age
foreach a of numlist 23 33 42 46 50 55{
su uit [w=1/pObs_WS] if age==`a'
replace uit=(uit-r(mean))/r(sd) if age==`a'
}

* decompose
bys NCDSID: egen uibar=mean(uit) if uit!=.
gen vit=uit-uibar

* variances
ge uit2=uit^2  
ge vit2=vit^2
ge uibar2=uibar^2

* total
qui rifhdreg uit2 `Controls' [pweight=1/pObs_WS], rif(mean) cluster(id) rob
mat b = e(b)
mat b = b'
svmat b
qui su b1 if b1!=0
drop b1
mat define p= r(N)
qui estadd scalar Par=p[1,1]
est sto var_total

* within
qui rifhdreg vit2 `Controls' [pweight=1/pObs_WS], rif(mean) cluster(id) rob
mat b = e(b)
mat b = b'
svmat b
qui su b1 if b1!=0
drop b1
mat define p= r(N)
qui estadd scalar Par=p[1,1]
est sto var_within

* between
qui rifhdreg uibar2 `Controls' [pweight=1/pObs_WS], rif(mean) cluster(id) rob
mat b = e(b)
mat b = b'
svmat b
qui su b1 if b1!=0
drop b1
mat define p= r(N)
qui estadd scalar Par=p[1,1]
est sto var_between


* Table
local text prefoot( \cline{2-4})  posthead( \cline{2-4})
esttab var* using results/Tables/R_OLS_Var.tex, ///
se star(* 0.1 ** 0.05 *** 0.01) b(%9.3f) se(%9.3f) nonumbers collabels(none) ///
stats(x N Par rifmean, fmt(%11.0gc %11.0gc %11.0gc  %8.2f) labels(" " "Individual-year observations" "Parameters" "Variance")) ///
keep(Creativity CogAbility) order(Creativity CogAbility) refcat(Creativity ""  " " "", nolabel) ///
varlabels(Creativity Creativitiy CogAbility "Cognitive ability") cells(b(star fmt(3)) se(par) p(par([ ])) ".") nogaps  ///
mtitles("\ \ \ Total \ \ \ " "Within-individual" "Between-individual") frag replace `text'
est drop _all

restore
